<?php if (!defined('BASE')) die('App exit');
require_once BASE."/nex/core/common.nex.php";

class Nex
{
	public static function start($appName)
	{
		Manage::run($appName);
	}		

	public static function getNex()
	{
		return Manage::nex();
	}
}

class Manage
{
	private static $_instance;
	private static $_classes;
	private static $_appName;

	public function __construct($appName)
	{
		self::$_appName = $appName;
		//run done
		//$this->gen_appdir(self::$_appName);
	}

	private function gen_appdir($appName)
	{
		if (!is_writable(BASE))
		{
			die(BASE."can't write");
		}
		if(!is_dir(BASE.'/'.$appName))
		{
			$appDir = array('controller','view','model','libs');
			$sl = SL;
			foreach ($appDir as $key => $value)
			{
				mkdir(BASE."{sl}{$appName}{sl}{$value}",0777,true);
			}
		}
	}

	public static function run($appName)
	{
		//func run
		if (!isset(self::$_instance))
		{
			self::$_instance = new Manage($appName);
			Nex::getNex()->gen_appdir($appName);
			Nex::getNex()->start();
		}
		else
		{

		}
	}

	public function start()
	{
		if (isset($_SERVER['PATH_INFO']))
		{
			$path = explode('/', $_SERVER['PATH_INFO']);
			if (empty($path[1]))
			{
				$this->load_controller(defController)->index();
			}
			else
			{
				$this->dispatch($path);
			}
		}
		else
		{
			$this->load_controller(defController)->index();
		}
	}

	public function dispatch($path)
	{
		$controller = $this->load_controller($path[1]);
		$path  = array_slice(array_slice($path, 1),1);
		$func = $path[0];
		$path = array_slice($path, 1);
		$controller->$func();
	}

	public static function nex()
	{
		if (isset(self::$_instance))
		{
			return self::$_instance;
		}else{
			self::$_instance = new Manage(self::$_appName);
		}
	}

	//
	public function load($class='null',$args=array())
	{
		if(!class_exists($class))
		{
			$this->import_class($class);	
		}
		$class = new ReflectionClass($class);
        return $class->newInstanceArgs($args);
	}


	private function import_class($class)
	{
		$class_tag = '.class.php';
		$path = array(self::$_appName,'nex');
		foreach ($path as $key => $value)
		{
			$require_path =BASE.SL.$value.SL.'libs'.SL.$value.$class_tag;
			if(require_once($require_path))
			{
				break;
			}
		}
	}	
	private function is_index()
	{

	}
	private function load_controller($controller='',$args = array())
	{
		$controller_path = BASE.SL.self::$_appName.SL.'controller'.SL."{$controller}".'.class.php';
		require_once($controller_path);
		$class = ucfirst($controller);

		$class = new ReflectionClass($class);
        return $class->newInstanceArgs($args);
	}
}

class NEXController
{
	//nomal function 
	public function __construct()
	{

	}
	protected function load($class='')
	{
		Nex::getNex()->load($class);
	}
	public function index()
	{

	}
}
